<?php

namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
/**
 * This is the model class for table "Banner".
 *
 */
class Banner extends ActiveRecord
{
    public $type;//操作类型

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%banner}}';
    }



    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title','url','pic','info'], 'trim'],
            [['id','mid','title','url','pic','type','sorts'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','type','mid','sorts'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'banner id',
            'mid'=>'模块',
            'title'=>'标题',
            'url'=>'链接',
            'type' => '操作类型',
            'pic'=>'图片',
            'info'=>'简介',
            'sorts'=>'排序',
        ];
    }



    public function scenarios()
    {
        return [
            'update_status' => [
                'id',
                'type',
            ],
            'default' => [
                'mid',
                'title',
                'url',
                'status',
                'type',
                'pic',
                'info',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'create' => [
                'mid',
                'title',
                'url',
                'status',
                'pic',
                'info',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update' => [
                'id',
                'mid',
                'title',
                'url',
                'status',
                'pic',
                'info',
                'sorts',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
        ];
    }



    /**
     * 获取banner列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getBannerList($params){
        if( isset($params['status']) && $params['status']!='' && !empty($params['title'])){
            $condition= ['and','banner.status='.intval($params['status']),['like','banner.title',$params['title']],['banner.deleted_at'=>null]];
        }elseif( isset($params['status']) && $params['status']!=''){
            $condition['banner.status']=intval($params['status']);
        }elseif(!empty($params['title'])){
            $condition = ['and',['like','banner.title',$params['title']],['banner.deleted_at'=>null]];
        }else{
            $condition = ['banner.deleted_at'=>null];
        }
        $list = (new Query())
            ->select('banner.id,banner.title,banner.pic,banner.info,banner.url,banner_class.title as class_title,banner.mid,banner.status,banner.sorts')
            ->from('banner')
            ->innerJoin('banner_class','banner_class.id=banner.mid')
            ->where($condition)
            ->orderBy('banner.sorts ASC,banner.id DESC')
            ->all();
//        if(count($list)){
//            foreach($list as $key=>$value){
//                switch ($value['mid']) {
//                    case 1:
//                        $list[$key]['mid']='项目';
//                        break;
//                    case 2:
//                        $list[$key]['mid']='模块';
//                        break;
//                    case 3:
//                        $list[$key]['mid']='操作';
//                        break;
//                }
//           }
//        }
        return empty($list)?array():$list;

    }


    /**
     * 删除与停启用banner
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editBannerState($param){
        $model = static::findOne(['id' =>$param['id']]);
        if(empty($model)) return array('error'=>'未查询到相关信息');
        $model->scenario = 'update';
        if($param['type']>1){ //删除
            $data['status']=2;
            $data['deleted_at'] = time();
        }else{ // 编辑停启用
            $info = $model->toArray();
            if($info['status']==1){
                $data['status'] = 0;
            }elseif($info['status']==0){
                $data['status'] = 1;
            }else{
                return array('error'=>'参数错误,请重新刷新页面再次请求');
            }

        }
        $model->setAttributes($data, false);
        if (!$model->save()) {
            return array('error'=>'操作失败');
        }else{
            return array('error'=>'');
        }

    }

    /**
     * 新增与编辑Banner 信息
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editBannerInfo($param){
        $t = static::getDb()->beginTransaction();
        try {
            if($param['type']>1){ //编辑
                $model = static::findOne(['id' =>$param['id']]);
                if(empty($model)) return array('error'=>'未查询到相关数据信息');
                $model->scenario = 'update';
            }else{ //新增
                $model = new self();
                $model->scenario = 'create';
                unset($param['id']);
            }
            $model->setAttributes($param, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }

    /**
     * 获取banner分类列表
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getBannerClassList(){
        $list = (new Query())
            ->select('*')
            ->from('banner_class')
            ->where(['deleted_at'=>null])
            ->all();
        return empty($list)?array():$list;

    }




}
